package middle;

public class Solution_209 {

    public int minSubArrayLen(int target, int[] nums) {
        long[] prefix = new long[nums.length];
        for (int i = 0; i < nums.length; i++) {
            prefix[i] = (i == 0 ? 0 : prefix[i - 1]) + nums[i];
        }

        int length = Integer.MAX_VALUE;
        for (int left = 0, right = 0; left < nums.length; ) {
            long sub = prefix[right] - (left > 0 ? prefix[left - 1] : 0);
            if (sub >= target) {
                length = Math.min(length, right - left + 1);
                left++;
            } else {
                right++;
                if (right == nums.length) {
                    break;
                }
            }
        }
        return length == Integer.MAX_VALUE ? 0 : length;
    }

    public static void main(String[] args) {
        Solution_209 model = new Solution_209();
        System.out.println(model.minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3}));
        System.out.println(model.minSubArrayLen(4, new int[]{1, 4, 4}));
        System.out.println(model.minSubArrayLen(11, new int[]{1, 1, 1, 1, 1, 1, 1, 1}));
    }
}
